<template>
  <span :tabindex="disabled ? null : 0" :class="wrapClasses" @click="toggle" @keyup.space.stop.prevent="toggle">
    <span :class="innerClasses">
      <span v-if="currentValue === trueValue" v-cloak>{{trueLabel}}</span>
      <span v-else v-cloak>{{falseLabel}}</span>
    </span>
  </span>
</template>
<script>
  const prefixCls = 'va-df-switch'

  /*
  * field配置
  *   trueValue
  *   falseValue
  *   trueLabel: string
  *   falseLabel: string
  *   size: ['large', 'small', 'default']
  *   disabled
  * */
  export default {
    props: {
      value: {
        default: false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      field: {
        default () {
          return {}
        }
      }
    },
    data () {
      return {
        currentValue: this.value
      }
    },
    computed: {
      wrapClasses () {
        return [
          `${prefixCls}`,
          {
            [`${prefixCls}-checked`]: this.currentValue === this.trueValue,
            [`${prefixCls}-disabled`]: this.disabled,
            [`${prefixCls}-${this.size}`]: !!this.size
          }
        ]
      },
      innerClasses () {
        return `${prefixCls}-inner`
      },
      trueValue () {
        return this.field.trueValue === undefined ? true : this.field.trueValue
      },
      falseValue () {
        return this.field.falseValue === undefined ? false : this.field.falseValue
      },
      trueLabel () {
        return this.field.trueLabel === undefined ? '开' : this.field.trueLabel
      },
      falseLabel () {
        return this.field.falseLabel === undefined ? '关' : this.field.falseLabel
      },
      size () {
        return ['large', 'small', 'default'].indexOf(this.field.size) > -1 ? this.field.size : 'default'
      }
    },
    methods: {
      toggle () {
        if (this.disabled) {
          return false
        }

        const checked = this.currentValue === this.trueValue ? this.falseValue : this.trueValue

        this.currentValue = checked
        this.$emit('input', checked)
      }
    },
    watch: {
      value (val) {
        this.currentValue = val
      }
    }
  }
</script>
